<template>
  <a-modal
    title="导入图形数据"
    :visible="visible"
    :width="800"
    :confirmLoading="importing"
    @ok="handleImport"
    @cancel="handleCancel"
    okText="导入"
    cancelText="取消"
  >
    <div class="import-dialog">
      <a-alert
        message="导入说明"
        description="请将序列化的JSON数据粘贴到下面的输入框中，然后点击导入按钮。导入会清空当前画布并加载新的数据。"
        type="info"
        show-icon
        style="margin-bottom: 16px;"
      />
      
      <a-form layout="vertical">
        <a-form-item label="JSON数据">
          <a-textarea
            v-model="jsonData"
            :rows="15"
            placeholder="请粘贴序列化的JSON数据..."
            :disabled="importing"
          />
        </a-form-item>
      </a-form>
      
      <div class="import-actions">
        <a-button @click="loadSampleData" :disabled="importing">
          加载示例数据
        </a-button>
        <a-button @click="clearData" :disabled="!jsonData || importing">
          清空数据
        </a-button>
        <a-button @click="validateData" :disabled="!jsonData || importing">
          验证数据
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<script>
export default {
  name: 'ImportDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      jsonData: '',
      importing: false
    }
  },
  methods: {
    /**
     * 处理导入
     */
    async handleImport() {
      if (!this.jsonData.trim()) {
        this.$message.warning('请输入JSON数据')
        return
      }

      this.importing = true
      
      try {
        // 解析JSON数据
        const parsedData = JSON.parse(this.jsonData.trim())
        
        // 验证数据结构
        if (!this.validateDataStructure(parsedData)) {
          this.$message.error('数据格式不正确，请检查JSON结构')
          return
        }

        // 触发导入事件
        this.$emit('import', parsedData)
        
        // 清空输入框
        this.jsonData = ''
        
        this.$message.success('数据导入成功')
      } catch (error) {
        console.error('导入错误:', error)
        this.$message.error('JSON格式错误，请检查数据格式')
      } finally {
        this.importing = false
      }
    },

    /**
     * 验证数据结构
     */
    validateDataStructure(data) {
      // 检查是否包含必要的字段
      if (!data || typeof data !== 'object') {
        return false
      }

      // 检查是否包含graph字段
      if (!data.graph || typeof data.graph !== 'object') {
        return false
      }

      // 检查graph是否包含cells字段
      if (!data.graph.cells || !Array.isArray(data.graph.cells)) {
        return false
      }

      return true
    },

    /**
     * 验证数据
     */
    validateData() {
      if (!this.jsonData.trim()) {
        this.$message.warning('请输入JSON数据')
        return
      }

      try {
        const parsedData = JSON.parse(this.jsonData.trim())
        
        if (this.validateDataStructure(parsedData)) {
          const nodeCount = parsedData.graph.cells.filter(cell => cell.shape === 'rect' || cell.shape === 'circle' || cell.shape === 'diamond').length
          const edgeCount = parsedData.graph.cells.filter(cell => cell.shape === 'edge').length
          
          this.$message.success(`数据验证通过！包含 ${nodeCount} 个节点，${edgeCount} 条连线`)
        } else {
          this.$message.error('数据格式不正确')
        }
      } catch (error) {
        this.$message.error('JSON格式错误')
      }
    },

    /**
     * 加载示例数据
     */
    loadSampleData() {
      const sampleData = {
        "graph": {
          "cells": [
            {
              "id": "start-node",
              "shape": "rect",
              "x": 100,
              "y": 200,
              "width": 80,
              "height": 40,
              "attrs": {
                "body": {
                  "stroke": "#52C41A",
                  "strokeWidth": 2,
                  "fill": "#F6FFED",
                  "rx": 8,
                  "ry": 8
                },
                "label": {
                  "text": "开始",
                  "fill": "#262626",
                  "fontSize": 14,
                  "fontWeight": 500
                }
              },
              "ports": {
                "groups": {
                  "in": {
                    "position": "left",
                    "attrs": {
                      "circle": {
                        "r": 4,
                        "magnet": true,
                        "stroke": "#52C41A",
                        "strokeWidth": 2,
                        "fill": "#fff"
                      }
                    }
                  },
                  "out": {
                    "position": "right",
                    "attrs": {
                      "circle": {
                        "r": 4,
                        "magnet": true,
                        "stroke": "#52C41A",
                        "strokeWidth": 2,
                        "fill": "#fff"
                      }
                    }
                  }
                },
                "items": [
                  { "group": "in", "id": "in" },
                  { "group": "out", "id": "out" }
                ]
              }
            },
            {
              "id": "end-node",
              "shape": "rect",
              "x": 400,
              "y": 200,
              "width": 80,
              "height": 40,
              "attrs": {
                "body": {
                  "stroke": "#F5222D",
                  "strokeWidth": 2,
                  "fill": "#FFF1F0",
                  "rx": 8,
                  "ry": 8
                },
                "label": {
                  "text": "结束",
                  "fill": "#262626",
                  "fontSize": 14,
                  "fontWeight": 500
                }
              },
              "ports": {
                "groups": {
                  "in": {
                    "position": "left",
                    "attrs": {
                      "circle": {
                        "r": 4,
                        "magnet": true,
                        "stroke": "#F5222D",
                        "strokeWidth": 2,
                        "fill": "#fff"
                      }
                    }
                  },
                  "out": {
                    "position": "right",
                    "attrs": {
                      "circle": {
                        "r": 4,
                        "magnet": true,
                        "stroke": "#F5222D",
                        "strokeWidth": 2,
                        "fill": "#fff"
                      }
                    }
                  }
                },
                "items": [
                  { "group": "in", "id": "in" },
                  { "group": "out", "id": "out" }
                ]
              }
            },
            {
              "id": "edge-1",
              "shape": "edge",
              "source": {
                "cell": "start-node",
                "port": "out"
              },
              "target": {
                "cell": "end-node",
                "port": "in"
              },
              "attrs": {
                "line": {
                  "stroke": "#5F95FF",
                  "strokeWidth": 2,
                  "targetMarker": {
                    "name": "block",
                    "width": 12,
                    "height": 8
                  }
                }
              },
              "router": {
                "name": "manhattan"
              },
              "connector": {
                "name": "rounded"
              }
            }
          ]
        },
        "businessData": {
          "start-node": {
            "nodeType": "start",
            "inputVariables": [],
            "outputVariables": [
              {
                "name": "data",
                "type": "string",
                "value": "test"
              }
            ]
          },
          "end-node": {
            "nodeType": "end",
            "inputVariables": [
              {
                "name": "data",
                "type": "string",
                "value": ""
              }
            ],
            "outputVariables": []
          }
        }
      }
      
      this.jsonData = JSON.stringify(sampleData, null, 2)
      this.$message.success('示例数据已加载')
    },

    /**
     * 清空数据
     */
    clearData() {
      this.jsonData = ''
      this.$message.info('已清空数据')
    },

    /**
     * 处理取消
     */
    handleCancel() {
      this.jsonData = ''
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
.import-dialog {
  padding: 8px 0;
}

.import-actions {
  margin-top: 16px;
  text-align: right;
}

.import-actions .ant-btn {
  margin-left: 8px;
}
</style> 